﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Xml;
using System.Xml.Serialization;
using Autofac;
using Autofac.Configuration;
using Tilver.ConsoleTest.Autofac;
using Tilver.ConsoleTest.Model;
using Tilver.ConsoleTest.Xml;

namespace Tilver.ConsoleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Begin to input command!");
            try
            {
                //命令控制循环
                while (true)
                {

                    Console.Write(">");
                    string cmd = Console.ReadLine();

                    if (cmd.ToLower() == "exit")
                    {
                        break;
                    }
                    if (cmd.ToLower() == "yield")
                    {
                        foreach (int i in Power(2, 8))
                        {
                            Console.WriteLine("{0} ", i);
                        }
                        continue;
                    }
                    if (cmd.ToLower().IndexOf("thread") != -1)
                    {
                        #region 线程测试

                        MyThread t = new MyThread(5);
                        ThreadStart threadStart = new ThreadStart(t.Calculate);
                        Thread thread = new Thread(threadStart);
                        thread.Start();

                        #endregion
                        continue;
                    }
                    if (cmd.ToLower().IndexOf("event") != -1)
                    {
                        #region 事件与委托

                        EventPublisher publisher = new EventPublisher();
                        EventReader1 r1 = new EventReader1(publisher);
                        EventReader2 r2 = new EventReader2(publisher);
                        publisher.DoSomthing();

                        #endregion
                        continue;
                    }
                    if (cmd.ToLower().IndexOf("autofac") != -1)
                    {
                        #region 依赖注入

                        /*
                     通过ContainerBuilder方法RegisterType对DatabaseManager进行注册，当注册的类型在相应得到的容器中可以Resolve你的DatabaseManager实例。
                     builder.RegisterType<SqlDatabase>().As<IDatabase>();通过AS可以让DatabaseManager类中通过构造函数依赖注入类型相应的接口。
                     Build()方法生成一个对应的Container实例，这样，就可以通过Resolve解析到注册的类型实例。
                     */
                        var builder = new ContainerBuilder();
                        builder.RegisterType<DatabaseManager>();
                        //builder.RegisterType<SqlDatabase>().As<IDatabase>();
                        //builder.RegisterType<OracleDatabase>().As<IDatabase>();
                        builder.RegisterModule(new ConfigurationSettingsReader("autofac"));
                        using (var container = builder.Build())
                        {
                            var manager = container.Resolve<DatabaseManager>();
                            manager.Search("SELECT * FORM USER");
                        }

                        #endregion
                        continue;
                    }
                    if (cmd.ToLower().IndexOf("model_builder") != -1)
                    {
                        #region 设计模式－建造者模式

                        Director director = new Director();
                        Builder b1 = new ConcreteBuilder1();
                        Builder b2 = new ConcerteBulider2();
                        director.Construct(b1);
                        Product p1 = b1.GetResult();
                        p1.Show();
                        director.Construct(b2);
                        Product p2 = b2.GetResult();
                        p2.Show();

                        #endregion
                        continue;
                    }
                    if (cmd.ToLower().IndexOf("model_observer") != -1)
                    {
                        #region 设计模式－观察者模式

                        //实例化主题
                        ConcreteAbstractSubject s = new ConcreteAbstractSubject();
                        //添加观察者
                        s.Attach(new ConcreteAbstractObserver(s, "X"));
                        s.Attach(new ConcreteAbstractObserver(s, "Y"));
                        s.Attach(new ConcreteAbstractObserver(s, "Z"));
                        //修改主题状态
                        s.SubjectState = "ABC";
                        //通知观察者
                        s.Notify();

                        #endregion

                        continue;
                    }
                    if (cmd.ToLower().IndexOf("model_factory") != -1)
                    {
                        #region 设计模式－抽象工厂模式

                        User user = new User();
                        Department dpt = new Department();
                        IFactory facatory = new AccessFactory();
                        IUser iu = facatory.CreateUser();
                        iu.Insert(user);
                        iu.GetUser(1);
                        IDepartment id = facatory.CreateDepartment();
                        id.Insert(dpt);
                        id.GetDepartment(1);

                        IFactory sqlFactory = new SqlServerFactory();
                        IUser sqlU = sqlFactory.CreateUser();
                        sqlU.Insert(user);
                        sqlU.GetUser(1);
                        IDepartment idD = sqlFactory.CreateDepartment();
                        idD.Insert(dpt);
                        idD.GetDepartment(1);

                        #endregion
                        continue;
                    }
                    if (cmd.ToLower().IndexOf("model_proxy") != -1)
                    {
                        #region 设计模式－代理模式

                        Proxy proxy = new Proxy();
                        proxy.Request();
                        Console.ReadKey();

                        #endregion
                        continue;
                    }
                    if (cmd.ToLower().IndexOf("xmlserialize") != -1)
                    {
                        #region 序列化

                        var project = new DataProject();
                        var xmlSerializer = new XmlSerializer(typeof(DataProject));
                        using (var writer = new XmlTextWriter(@".\.tiv", Encoding.UTF8))
                        {
                            xmlSerializer.Serialize(writer, project);
                        }
                        #endregion
                        continue;
                    }
                    if (cmd.ToLower().IndexOf("regex") != -1)
                    {
                        #region 正则表达式
                        string source = "「sdfgA」中国「sfg」lkadl喀「」什";//Console.ReadLine();
                        Regex regex = new Regex("「[a-zA-Z]+」", RegexOptions.IgnoreCase);
                        string result = regex.Replace(source, match => string.Format("<a>{0}</a>", match.Value));
                        Console.WriteLine("{0} ", result);
                        #endregion
                        continue;
                    }
                } //end of while
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
        public static System.Collections.IEnumerable Power(int number, int exponent)
        {
            int result = 1;
            for (int i = 0; i < exponent; i++)
            {
                result = result * number;
                yield return result;
            }
        }

        #region 事件与委托
        /// <summary>
        /// 事件发布者
        /// </summary>
        public class EventPublisher
        {
            /// <summary>
            /// 申明委托（函数指针）
            /// </summary>
            /// <param name="message"></param>
            /// <returns></returns>
            public delegate int SampleEventDelegate(string message);
            /// <summary>
            /// 申明与委托相关的事件
            /// </summary>
            public event SampleEventDelegate SampleEvent;
            public void DoSomthing()
            {
                if (this.SampleEvent != null)
                {
                    this.SampleEvent("Hello world!");
                }
            }
        }
        public class EventReader1
        {
            public EventReader1(EventPublisher publisher)
            {
                publisher.SampleEvent += new EventPublisher.SampleEventDelegate(publisher_SampleEvent);
            }

            int publisher_SampleEvent(string message)
            {
                Console.WriteLine(string.Format("{0} --- This is form reader1", message)); return 0;
            }
        }
        public class EventReader2
        {
            public EventReader2(EventPublisher publisher)
            {
                publisher.SampleEvent += new EventPublisher.SampleEventDelegate(publisher_SampleEvent);
            }

            int publisher_SampleEvent(string message)
            {
                Console.WriteLine(string.Format("{0} --- This is form reader2", message)); return 0;
            }
        }
        #endregion

    }
}
